<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity {

	public $email;
	
	/**
	 * @var User the user of this identity.
	 */
	private $_user = null;
	private $_id = null;

	/**
	 * Constructor.
	 * @param string $email username
	 * @param string $password password
	 */
	public function __construct($email, $password) {
		$this->email = $email;
		$this->password = $password;
	}

	/**
	 * Authenticates a user.
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate() {
		$this->_user = User::model()->findByAttributes(array('email' => $this->email));
		if($this->_user === null) {
			$this->errorCode = self::ERROR_USERNAME_INVALID;
		} else if($this->_user->password !== User::hashPassword($this->password)) {
			$this->errorCode = self::ERROR_PASSWORD_INVALID;
		} else {
			$this->username = $this->_user->name;
			$this->_id = $this->_user->id;
			$this->errorCode = self::ERROR_NONE;
		}
		return $this->errorCode === self::ERROR_NONE;
	}

	/**
	 * Returns the unique identifier for the identity.
	 * @return int primary key of User. null if the user does not exist.
	 */
	public function getId() {
		return $this->_id;
	}

	/**
	 * @return User the User for this indentity.
	 */
	public function getUser() {
		return $this->_user;
	}

}